package phoenixAAD.WifiFlashDrive;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class Server extends Thread
{
	public static final int PROTOCOL_END = 100;
	
	private int listenPort;
	private ServerSocket server;
	private ArrayList<Protocol> clients = new ArrayList<Protocol>();
	private boolean isRunning = true;
	private String username;
	private String password;
	private final String rootDirectory;
	private final FTP ftp;
	private final String ENCODING;
	
	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}

	private Handler toServer = new ServerHandler();
	
	public Server(int port, String rootDirectory, FTP ftp, String encoding) throws IOException
	{
		this.ENCODING = encoding;
		this.ftp = ftp;
		this.rootDirectory = rootDirectory;
		listenPort = port;
		server = new ServerSocket(listenPort);
	}
	

	public void run()
	{
		try
		{
			ftp.sendLog(ftp.getResources().getString(R.string.status_server_accepting));
			while(isRunning)
			{
				Protocol newClient = new Protocol(server.accept(), toServer, rootDirectory, ftp, ENCODING);
				newClient.setUsername(username);
				newClient.setPassword(password);
				newClient.start();
				clients.add(newClient);
	
				
				ftp.sendLog(ftp.getResources().getString(R.string.status_client_connected));
			}
		}
		catch (IOException e) {}
	}
	
	
	public void close()
	{
		System.out.println("server stopping");
		ftp.sendLog(ftp.getResources().getString(R.string.status_shutdown_control));
		try {

			isRunning = false;
			if(server != null)
				server.close();
		} catch (IOException e) {}
		
		// kill all connections to client
		for(Protocol client : clients)
		{
			if(client.close())
			{
				try {
					client.interrupt();
					client.join();
				} catch (InterruptedException e) {
				}
			}
		}
		ftp.sendLog(ftp.getResources().getString(R.string.status_control_offline));
		System.out.println("server stopped");
	}
	

	/**
	 * Handler for stopping the protocol thread and removing it from client arraylist
	 */
	private class ServerHandler extends Handler
	{

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what)
			{
			case PROTOCOL_END:
			{
				Protocol finishedProtocol = (Protocol) msg.obj;
				finishedProtocol.close();
				try {
					finishedProtocol.join();
				} catch (InterruptedException e) {}
				if(!clients.remove(finishedProtocol))
					throw new RuntimeException("a client was not removed from communication server");
				break;
			}
			default:
				throw new RuntimeException("Communication server handler received and unknown message");
			}
		}
		
	}
	
	/**
	 * Returns if there are transfers in progress
	 */
	public boolean isTransferring()
	{
		for(Protocol client : clients)
		{
			if(client.isTransferring())
				return true;
		}
		return false;
	}
}
